#!/usr/bin/python
# -*- coding: UTF-8 -*-

import smtplib
from email.mime.text import MIMEText
from email.header import Header
from config.config import (
    MAIL_HOST,
    MAIL_USER,
    MAIL_PASSWD,
    MAIL_SUBJECT,
    MAIL_SENDER,
    MAIL_RECEIVER,
    MAIL_EXPIRE,
)
from utils.redis.redis import GetInstance
from utils.log.log import Log
from utils.utils import isWindows

log = Log("smtp model")


class Smtp(object):
    """Smtp for message"""

    def __init__(self):
        super(Smtp, self).__init__()
        self.sender = MAIL_SENDER
        self.host = MAIL_HOST
        self.user = MAIL_USER
        self.passwd = MAIL_PASSWD
        self.subject = MAIL_SUBJECT
        self.conn = GetInstance()

    def Send(self, msg, receiver=MAIL_RECEIVER, expire=MAIL_EXPIRE):
        """Send(self, msg, receiver=MAIL_RECEIVER{},  expire=MAIL_EXPIRE int)"""
        try:
            smtpObj = smtplib.SMTP_SSL(self.host, 465)
            smtpObj.login(self.user, self.passwd)

            message = MIMEText(msg, "plain", "utf-8")
            message["From"] = Header(self.user, "utf-8")
            message["Subject"] = Header(self.subject, "utf-8")
            msgstr = message.as_string()
            hash = msgstr.__hash__()
            # 判断下有没有超时,windows下不管
            if isWindows() == False:
                if self.conn.get(hash) != None:
                    log.Debug("mail expire is send already in ", MAIL_EXPIRE)
                    return True
                else:
                    log.Debug("mail goto send new ")
                    self.conn.set(hash, "mail_expire_set")
                    self.conn.expire(hash, MAIL_EXPIRE)
            for dst in receiver:
                message["To"] = Header(dst, "utf-8")
                ret = smtpObj.sendmail(self.sender, dst, msgstr)
            return True
        except Exception as e:
            print("sendmail failed ", e)
        return False
